const express = require("express");
const Router = express.Router();
const tools = require("./tools");
const models = require("./model");
const User = models.getModel("user");
const Chat = models.getModel("chat");
const filter_pwd = {pwd: 0};


/*
* 查询用户聊天信息
* */
Router.get('/msgList', (req, res) => {
  const {userId} = req.cookies;
  if (!userId) {
    return res.json({code: 1, msg: "用户未登录!"});
  }
  User.find({}, (e, userArr) => {
    if (e) {
      return res.json({code: 1, msg: '用户查询失败'});
    }
    let users = {};
    userArr.forEach(u => {
      users[u._id] = {avatar: u.avatar, username: u.username};
    });
    Chat.find({'$or': [{from: userId}, {to: userId}]}, (err, doc) => {
      if (err) {
        return res.json({code: 1, msg: "查询出错"});
      }
      return res.json({code: 0, data: {users, chatMsgList: doc}});
    })
  });

});

/*
* 读消息
* */
Router.post('/msgRead', (req, res) => {
  const {userId} = req.cookies;
  if (!userId) {
    return res.json({code: 1, msg: "用户未登录或登录过期!"});
  }
  const {from} = req.body;
  Chat.update(
    {from, to: userId},
    {'$set': {read: true}},
    {'multi': true},
    function (err, result) {
      if (err) {
        return res.json({code: 1, msg: '数据库操作失败'})
      }
      return res.json({
        code: 0,
        num: result.nModified
      });
    });
});

/*
* 查询数据库所有用户
* */
Router.get("/list", (req, res) => {
  const {userId} = req.cookies;
  if (!userId) {
    return res.json({code: 1, msg: "用户验证失败!"});
  }
  const {role} = req.query;
  User.find({role}, filter_pwd, (err, doc) => {
    if (err) {
      return res.json({code: 1, msg: "查询数据库出错!"});
    } else {
      return res.json({code: 0, data: doc});
    }
  });
});


/*
* 注册
* */
Router.post("/register", (req, res) => {
  const {username, pwd, role} = req.body;
  User.findOne({username}, (err, doc) => {
    if (err) {
      return res.json({code: 1, msg: "注册失败!"});
    }
    if (doc) {
      return res.json({code: 1, msg: "用户名已存在!"});
    }
    const info = {username, role, pwd: tools.md5(pwd)};
    const userModel = new User(info);
    userModel.save((err, doc) => {
      if (err) {
        return res.json({code: 1, msg: "用户存储失败!"});
      }
      const {username, _id, role} = doc;
      res.cookie("userId", _id);
      return res.json({code: 0, data: {username, role, _id}});
    });
  });
});


/*
* 登录
* */
Router.post("/login", (req, res) => {
  const {username, pwd} = req.body;
  User.findOne({username, pwd: tools.md5(pwd)}, filter_pwd, (err, doc) => {
    if (err) {
      return res.json({code: 1, msg: "登录失败"});
    }
    if (!doc) {
      return res.json({code: 1, msg: "用户名或密码错误"});
    }
    res.cookie("userId", doc._id);
    return res.json({code: 0, data: doc});
  });

});


/*
* 更新修改用户信息
* */
Router.post("/update", (req, res) => {
  const {userId} = req.cookies;
  if (!userId) {
    return res.json({code: 1, msg: "获取用户信息失败!"});
  }
  User.findByIdAndUpdate({_id: userId}, req.body, {
    new: true,
    select: filter_pwd
  }, (err, doc) => {
    if (err) {
      return res.json({code: 1, msg: err.toString()});
    }
    return res.json({code: 0, data: doc});
  });

});


/*
* 获取用户登录状态
* */
Router.get("/info", function (req, res) {
  const {userId} = req.cookies;
  if (!userId) {
    return res.json({code: 1, msg: "用户未登录!"});
  }
  User.findOne({_id: userId}, filter_pwd, (err, doc) => {
    if (err) {
      return res.json({code: 1, msg: "获取用户信息异常"});
    }
    if (!doc) {
      return res.json({code: 1, msg: "未获取到用户信息"});
    }
    return res.json({code: 0, data: doc});
  });
});


module.exports = Router;